import allRoutes from '@/router/allRoutes'
import type { RouteRecordRaw } from 'vue-router'
let firstMenu: any = null
export default function mapMenuToRoutes(menus: any[]): RouteRecordRaw[] {
  const activeRoutes: RouteRecordRaw[] = []
  const _findRoute = (menu) => {
    menu.forEach((item) => {
      if (item.type === 2) {
        const targetRoute = allRoutes.find((route) => route.path === item.url)
        if (targetRoute) {
          if (!firstMenu) firstMenu = targetRoute
          activeRoutes.push(targetRoute)
        }
      } else {
        _findRoute(item.children)
      }
    })
  }

  _findRoute(menus)
  return activeRoutes
}
export function mapToBreadArr(menus: any[], currentPath: string) {
  const breadcrumbArr: any[] = []
  findActiveRoute(menus, currentPath, breadcrumbArr)
  return breadcrumbArr
}
export function findActiveRoute(menus: any[], currentPath: string, breadcrumbArr?: any[]) {
  for (const menu of menus) {
    if (menu.type === 1) {
      const findMenu = findActiveRoute(menu.children ?? [], currentPath)
      if (findMenu) {
        breadcrumbArr?.push({ name: menu.name })
        breadcrumbArr?.push({ name: findMenu.name })
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export function mapToPermission(menus: any[]) {
  const allPermission: string[] = []
  const _recurveMapPermission = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 1 || menu.type === 2) {
        _recurveMapPermission(menu.children ?? [])
      } else if (menu.type === 3) {
        allPermission.push(menu.permission)
      }
    }
  }

  _recurveMapPermission(menus)
  return allPermission
}
export { firstMenu }
